package top.yongyan0624.security;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
import top.yongyan0624.entity.SysUser;
import top.yongyan0624.service.SysUserService;
import top.yongyan0624.utils.JwtUtils;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author Yongyan
 * @description: TODO
 * @date 2021/5/12
 **/
public class JwtAuthenticationFilter extends BasicAuthenticationFilter {

    @Autowired
    private JwtUtils jwtUtils;

    @Autowired
    private UserDetailServiceImpl userDetailService;

    @Autowired
    private SysUserService sysUserService;

    public JwtAuthenticationFilter(AuthenticationManager authenticationManager) {
        super(authenticationManager);
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {

        String jwt = request.getHeader(jwtUtils.getHeader());
        if (StrUtil.startWith(jwt,"\"") && StrUtil.endWith(jwt,"\"")){
            jwt = StrUtil.sub(jwt, 1, jwt.length() - 1);
        }
        if (StrUtil.isBlankOrUndefined(jwt)) {
            //如果不存在jwt，直接往后面走，不进行jwt的自动认证
            chain.doFilter(request, response);
            return;
        }

        //存在jwt，进行解析
        Claims claims = jwtUtils.getClaimsByToken(jwt);
        if (claims == null) {
            //说明jwt不合法
            throw new JwtException("token 异常");
        }
        if (jwtUtils.isTokenExpired(claims)) {
            //token过期
            throw new JwtException("token 已过期");
        }

        //获取 claims 中的主体(username)
        String username = claims.getSubject();

        // 通过username获取user的id，用以获取user的权限信息
        SysUser sysUser = sysUserService.getOne(new QueryWrapper<SysUser>().eq("username",username));

        //获取用户的权限信息
        UsernamePasswordAuthenticationToken token =
                new UsernamePasswordAuthenticationToken(username, null, userDetailService.getUserAuthority(sysUser.getId()));

        //通过用户的权限信息完成自动登录
        SecurityContextHolder.getContext().setAuthentication(token);

        //放行
        chain.doFilter(request, response);
    }
}
